//
//  HMPhotoBrowerCollectionViewCell.swift
//  WeiBo
//
//  Created by apple on 16/7/6.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SDWebImage

protocol HMPhotoBrowerCollectionViewCellDelegate: NSObjectProtocol {
    
    func tapImageClose()
}

class HMPhotoBrowerCollectionViewCell: UICollectionViewCell {
    
    // 闭包属性
    var closure: (()->())?
    
    weak var delegate: HMPhotoBrowerCollectionViewCellDelegate?
    
    var photoViewModel: HMPhotoViewModel?{
        
        didSet{
            
            // 给小图赋值
            // 可以拿到图片的url
            
            guard let key = photoViewModel?.model?.thumbnail_pic else {
                return
            }
            // 通过SDWebImage 拿到小图
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            
            holderImageView.image = image
            holderImageView.hidden = false
            
            // 下载大图
            imageView.sd_setImageWithURL(changeToBigURL(key), placeholderImage: nil, options: [], progress: { (current, total) -> Void in
                
                
                printLog(NSThread.currentThread())
                // 要注意 progress是主线程还是子线程
                let persent = CGFloat(current) / CGFloat(total)
                
                self.holderImageView.progress = persent
                
                }) { (bigImage, error, _ , _) -> Void in
                    
                    // 图片下载完成的回调
                    printLog("下载完成")
                    self.showBigImageView(bigImage)
                    
                    // 下载完成之后,让缩略图隐藏
                    self.holderImageView.hidden = true
            }
        }
        
    }
    
    // 第一步 -- 重写构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 第二步 -- 定义一个方法,来实现 视图的添加和布局
    private func setupUI(){
        
        backgroundColor = RandomColor()
        contentView.addSubview(scrollView)
        contentView.addSubview(holderImageView)
        scrollView.addSubview(imageView)
        
//        scrollView.snp_makeConstraints { (make) -> Void in
//            make.center.equalTo(contentView.center)
//        }
        scrollView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        holderImageView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(contentView.center)
        }
        
        imageView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(scrollView.snp_center)
        }
        
        imageView.userInteractionEnabled = true
        
        let tap = UITapGestureRecognizer(target: self, action: "tapImageView")
        
        imageView.addGestureRecognizer(tap)
        
    }
    
    @objc private func tapImageView(){
        
        printLog("点击关闭")
        delegate?.tapImageClose()
    }
    
    //  把图片地址替换一下,变成大图地址
    private func changeToBigURL(urlString: String) -> NSURL{
        
        //http:\\\//ww4.sinaimg.cn/thumbnail/006d7ixQgw1f5hnf1tkz8j30gl4ettqs.jpg
        // http://ww4.sinaimg.cn/bmiddle/006d7ixQgw1f5hnf1tkz8j30gl4ettqs.jpg
        
        // 第一个参数:把字符串中要替换的字符
        // 第二个参数: 替换成的 字符串
      let newUrlString = (urlString as NSString).stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        
        return NSURL(string: newUrlString)!
    }
    
    
    
    // 显示大图
    private func showBigImageView(image: UIImage){
        

        
        // 设置宽度为屏幕的宽度
        let width = kUIScreenWidth
        let height = width / image.size.width * image.size.height
       // 设置一下x和y

        scrollView.contentSize = CGSizeMake(width, height)
        
        
    }
    
    
    func saveImage(){
        
        if let image = imageView.image {
            
            UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
            
        }
        
        
    }
   @objc func image(image: UIImage, didFinishSavingWithError: NSError?,contextInfo: AnyObject){
        
        // 在这个方法里保存成功了
    
   
    if didFinishSavingWithError == nil{
        
        // 进行闭包回调
        closure?()
    }

    
    }
    // - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    
    // 第三步: 懒加载控件
    private lazy var holderImageView: HMProgressView = {
    
        let img = HMProgressView(frame: CGRectZero)
        
        img.sizeToFit()
        
        return img
    }()
    
    // 创建一个UIScrollView
    private lazy var scrollView: UIScrollView = UIScrollView()
    
    // 
    private lazy var imageView: UIImageView = {
    
        let img = UIImageView()
        
        return img
    }()
}
